<template>
  <div>
    <!-- 行业招聘热度 -->
    <div class="top-title">
      <span class="tinyTitle">
        <div class="titleFlag"></div>
        {{ "行业招聘热度" }}
      </span>
    </div>
    <div class="top-line"></div>
    <el-row class="search-container">
      <el-form ref="form" label-width="auto">
        <el-form-item label="统计时间：">
          <el-date-picker
            v-model="selectBetweenTime"
            :clearable="false"
            size="small"
            type="monthrange"
            align="right"
            unlink-panels
            value-format="yyyy-MM-dd"
            range-separator="-"
            start-placeholder="开始月份"
            end-placeholder="结束月份"
            :picker-options="pickerOptions"
            @change="handleDateChange"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="行业名称：">
          <IndustryCheckbox
            :limitNum="1"
            ref="regionRef"
            :selectBetweenTime="selectBetweenTime"
            :selectIndustryType="2"
            @onIndustryChange="onIndustryChange"
          />
        </el-form-item>
      </el-form>
    </el-row>
    <div class="regionSalaryContent">
      <div class="echart">
        <div class="regionLineChart">
          <div class="chartMain">
            <template v-if="chartDataIsNotEmpty">
              <div class="h100" ref="line_echartDom"></div>
            </template>
            <el-empty class="empty" description="暂无数据" v-else
              ><el-button type="primary" size="mini" @click="handleKnowClick()">
                想要了解
              </el-button></el-empty
            >
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { reqCommonHeat } from "@/api/chart.js";
import IndustryCheckbox from "@/components/IndustryCheckbox/index";
import { reportLackDataPosition } from "@/api/salary";
export default {
  name: "industryRecruitHot",
  components: {
    IndustryCheckbox,
  },
  data() {
    return {
      chartData: {},
      chartDataIsNotEmpty: true, //必须让图表先显示，不然会出现空白
      average: "",
      isSetDeaultTime: false,
      selectedIndustryList: [],
      selectBetweenTime: [],
      pickerMinDate: "",
      firstDayofLastMonth: "",
      pickerOptions: {
        disabledDate: (time) => {
          const nowTime = time.getTime();
          if (nowTime < 1672502400000 || nowTime > this.firstDayofLastMonth) {
            return true;
          }
          if (this.pickerMinDate) {
            const monthsDiff =
              Math.abs(nowTime - this.pickerMinDate) /
              (1000 * 60 * 60 * 24 * 30);
            // 如果相差的月份大于6个月，则禁用该日期
            return monthsDiff > 6 || nowTime < 1672502400000;
          }
        },
        onPick: (obj) => {
          this.pickerMinDate = new Date(obj.minDate).getTime();
        },
      },
    };
  },
  created() {
    // 创建一个表示当前日期的 Date 对象
    var currentDate = new Date();

    // 将当前日期设置为本月的第一天
    currentDate.setDate(1);

    // 将当前日期减去一天，得到上个月最后一天
    currentDate.setDate(0);

    // 设置时间为零点
    currentDate.setHours(0, 0, 0, 0);

    // 获取时间戳
    var timestamp = currentDate.getTime();

    this.firstDayofLastMonth = timestamp;

    let date = new Date();
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let newYear = 0;
    let newMonth = 0;
    let newDateArr = [];
    for (let i = 0; i < 7; i++) {
      //这里是获取前六个月,所以循环6次,根据需要修改
      if (month - i < 1) {
        //这里的判断是如果当前月份往前推到了去年  需要做的处理
        newYear = year - 1;
        newMonth =
          month - i + 12 >= 10 ? month - i + 12 : "0" + (month - i + 12);
        newDateArr.push(newYear + "-" + newMonth + "-" + "01"); //这里拼接格式化,在时间中间加了个-,根据实际需求来
      } else {
        newMonth = month - i >= 10 ? month - i : "0" + (month - i); //这里是对月份小于10做加前面加0处理
        newDateArr.push(year + "-" + newMonth + "-" + "01");
      }
    }
    //这里就最后得到当前年月前六个月组成的时间数组,根据需要赋值使用即可
    const end = newDateArr[1];
    const start = newDateArr[6];
    this.selectBetweenTime = [start, end];
  },
  mounted() {
    this.fetchData();
  },
  methods: {
    fetchData() {
      const params = {
        ylPositionId: this.$route.query.id,
        keyType: "1", //1:国标行业 2:企业规模
        keyId: this.selectedIndustryList[0],
      };
      if (this.selectBetweenTime != null && this.selectBetweenTime != "") {
        params.startTime = this.selectBetweenTime[0];
        params.endTime = this.selectBetweenTime[1];
      }
      reqCommonHeat(params)
        .then((response) => {
          if (response.code == 200) {
            this.chartData = this.handleData(response.data);
            this.chartDataIsNotEmpty =
              response.data && response.data.length > 0;
            setTimeout(() => {
              this.init();
            }, 500);
          } else {
            this.chartDataIsNotEmpty = false;
          }
        })
        .catch(() => {
          this.chartDataIsNotEmpty = false;
        });
    },
    handleData(data) {
      // 因为后端数据结构改了 这里不可能再兼容多条折线了，如果你要多条折现那就去看reruitHeatLineChart吧
      // 2024年8月16日09:57
      let dataArr = {
        industry: [],
        time: [],
      };
      if (data && data.length) {
        const obj = {
          name: data[0].keyName,
          heatNum: [],
        };

        data.forEach((dataItem) => {
          obj.heatNum.push(dataItem.heatNum);
          dataArr.time.push(this.formatDate(dataItem.calMonth));
        }),
          dataArr.industry.push(obj);
      } else {
      }
      return dataArr;
    },
    formatDate(dateString) {
      // 解析日期字符串
      const date = new Date(dateString);

      // 获取月份和年份
      const month = date.getMonth() + 1; // getMonth() 返回 0-11，所以需要加 1
      const year = date.getFullYear();

      // 格式化为“6月2024”格式
      return `${month}月${year}`;
    },
    init() {
      if (!this.$refs["line_echartDom"]) return;
      this.myChart = this.$echarts.init(this.$refs["line_echartDom"]);
      let industry = this.chartData.industry;
      let time = this.chartData.time;

      let option = {
        color: [
          "#F359AE",
          "#34CA6F",
          "#066BFF",
          "#75E0FF",
          "#FFA506",
          "#3ba272",
          "#fc8452",
          "#9a60b4",
          "#ea7ccc",
        ],
        xAxis: {
          type: "category",
          data: time,
          name: "(月份)",
          // boundaryGap: false,
          axisLabel: {
            formatter(val) {
              // 当字符串长度超过2时
              if (val.length > 2) {
                // 把字符串分割成字符串数组
                const array = val.split("");
                const index = array.indexOf("月");
                //在下标2处删除0个，加上回车
                array.splice(index + 1, 0, "\n\n");
                return array.join("");
              } else {
                return val;
              }
            },
            color: "#8193B2",
            fontSize: "12px",
          },
          axisLine: {
            lineStyle: {
              color: "#E4EDF8",
            },
          },
          nameTextStyle: {
            lineHeight: 80, //标题行高
            color: "#8193B2",
            verticalAlign: "top", //标题位置
            fontSize: "12px", // 设置最大宽度
            padding: [-28, 0, 0, 0], // 上右下左与原位置距离
          },
        },
        tooltip: {
          trigger: "axis",
          // formatter(val) {
          //   //console.log("val", val[0]);

          //   return val[0].seriesName;
          // },
        },
        grid: {
          right: "50",
          bottom: "50",
          top: "50",
          left: "50",
        },
        yAxis: {
          type: "value",
          min: 20,
          max: 100,
          //   splitNumber: 5,
          // minInterval: 1,
          scale: true,
          name: "（热度值）",
          axisLabel: {
            color: "#8193B2",
            fontSize: "12px",
          },
          nameTextStyle: {
            padding: [0, 40, 10, 0], // 上右下左与原位置距离
            color: "#8193B2",
          },
        },
        series: [],
      };
      option.series = [];
      this.myChart.clear();
      industry.forEach((item, index) => {
        option.series.push({
          data: item.heatNum,
          name: item.name,
          type: "line",
          smooth: true,
          symbolSize: 10,
          symbol: "path://M349 889.5a7.5 7.5 0 1 0 15 0a7.5 7.5 0 1 0 -15 0z",
          showSymbol: false,
          label: {
            normal: {
              show: false,
            },
          },
          emphasis: {
            label: {
              // show: true,
            },
          },
        });
      });

      option && this.myChart.setOption(option);
      window.addEventListener("resize", () => {
        if (this.myChart) {
          this.myChart.resize();
        }
      });
      this.myChart.dispatchAction({
        type: "showTip",
        seriesIndex: 0,
        dataIndex: 1,
      });
    },
    onIndustryChange(val) {
      if (val && val.length) {
        this.selectedIndustryList = [];
        val.forEach((item) => {
          this.selectedIndustryList.push(item.split("-")[0]);
        });
      } else {
        this.selectedIndustryList = [];
      }
      this.fetchData();
    },
    handleDateChange(val) {
      if (this.isSetDeaultTime) {
        this.isSetDeaultTime = false;
        return;
      }
      this.pickerMinDate = null;
      this.fetchData();
    },
    handleKnowClick() {
      const userInfo = JSON.parse(localStorage.getItem('userInfo')); //OA的userInfo和SaaS登录的userInfo不一样
      const oaId = "";
      if (userInfo && userInfo.user_source_id) {
        oaId = userInfo.user_source_id;
      }
      const params = {
        positionId: this.$route.query.id,
        positionName: this.$route.query.name,
        layerId: "198",
        layerName: "行业招聘热度",
        personId: localStorage.getItem("personId") || "",
        oaId: oaId,
      };
      reportLackDataPosition(params).then((response) => {
        if (response.code == 200) {
          this.$message.success("已成功提交");
        } else {
          this.$message.error(res.status_desc);
        }
      });
    },
  },
};
</script>

<style scoped lang="scss">
.top-title {
  display: flex;
  margin: 20px 40px 10px 0px;
}
.tinyTitle {
  display: flex;
  align-items: center;
  font-size: 18px;
  color: #222;
  font-weight: bold;
  margin-right: 40px;

  .titleFlag {
    width: 5px;
    height: 15px;
    border-radius: 3px;
    background: #4880ff;
    margin-right: 12px;
  }
}
.top-line {
  height: 1px;
  background-color: #cfd8f5;
  margin: -24px 0px 20px 140px;
}
.regionSalaryContent {
  position: relative;
  display: flow-root;
  // margin-top: 20px;
  // max-height: calc(100vh - 192px);
  // overflow-y: scroll;

  // padding-right: 56px;
  &::-webkit-scrollbar {
    width: 4px;
    background-color: #fff;
    border-radius: 4px;

    height: 4px;
  }
  &::-webkit-scrollbar-thumb {
    background-color: #d8d8d8;
    border-radius: 4px;
  }
}
.regionLineChart {
  display: block;
  align-items: center;
  width: 100%;
}
// .regionLineChart {
//   flex: 1;
// }
.chartMain {
  display: flex;
  // align-items: center;
  margin-left: 0px;
  .empty {
    margin: auto;
    ::v-deep .el-empty__image {
      width: 150px;
    }
  }
}

.h100 {
  flex: 0.7;
  height: 20vw;
  width: 100%;

  min-width: 615px;
  min-height: 240px;
}

::v-deep .el-date-editor .el-range-input {
  background-color: transparent !important;
}
</style>
